<template>
  <div class="home-container">
    <el-container>
      <!-- 头部区域 -->
      <el-header>
        <h2 class="header-title">购物管理系统</h2>
      </el-header>

      <el-container>
        <!-- 侧边栏菜单 -->
        <el-aside width="200px">
          <el-menu
            :default-active="activeMenu"
            class="el-menu-vertical-demo"
            @select="handleMenuSelect"
          >
            <el-menu-item index="/adminhomeproduct">
              <i class="el-icon-goods"></i>
              <span>商品管理</span>
            </el-menu-item>
            <el-menu-item index="/adminhomeorder">
              <i class="el-icon-s-order"></i>
              <span>订单管理</span>
            </el-menu-item>
            <el-menu-item index="/adminhomeuser">
              <i class="el-icon-user"></i>
              <span>用户管理</span>
            </el-menu-item>
          </el-menu>
        </el-aside>
        <!-- 主内容区域 -->
        <el-main>
          <!-- 饼图区域 -->
          <div class="charts-container">
            <!-- 销售数量统计 -->
            <div id="sales-quantity-chart" class="chart"></div>
            <!-- 销售金额统计 -->
            <div id="sales-amount-chart" class="chart"></div>
          </div>

          <!-- 订单列表 -->
          <div class="small-title">订单列表</div>
          <el-table
            ref="multipleTable"
            :data="OrderData.data"
            tooltip-effect="dark"
            style="width: 100%; font-size: 20px"
            @selection-change="handleSelectionChange"
          >
            <el-table-column width="40"></el-table-column>
            <el-table-column label="商品图片" width="200">
              <template #default="scope">
                <img
                  :src="scope.row.image"
                  alt="SmallImage"
                  class="resized-image"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              label="商品名称"
              width="350"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="price"
              label="单价"
              width="140"
            ></el-table-column>
            <el-table-column
              prop="quantity"
              label="数量"
              width="100"
            ></el-table-column>
            <el-table-column label="小计" width="180">
              <template #default="scope">
                <div class="TotalPrice">
                  {{ scope.row.price * scope.row.quantity }}元
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="userId"
              label="用户id"
              width="100"
            ></el-table-column>
            <el-table-column label="购买时间" width="200">
              <template #default="scope">
                {{ formatDate(scope.row.purchaseTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="140">
              <template #default="scope">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="deleteCart(scope.row.id)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  data() {
    return {
      activeMenu: '/adminhomeorder', // 默认选中的菜单项
      OrderData: {}, // 商品数据
    }
  },
  mounted() {
    this.getOrderData()
  },
  watch: {
    'OrderData.data': function (newData) {
      if (newData && newData.length) {
        this.initCharts(newData) // 数据加载后初始化图表
      }
    },
  },
  methods: {
    handleMenuSelect(index) {
      console.log(`选中菜单项: ${index}`)
      this.activeMenu = index
      this.$router.push(index).catch((err) => {
        if (err.name !== 'NavigationDuplicated') {
          console.error(err)
        }
      })
    },
    formatDate(dateStr) {
      const date = new Date(dateStr)
      return date.toLocaleString()
    },
    async deleteCart(id) {
      try {
        const token = localStorage.getItem('jwtToken')
        const response = await this.$http.delete('/api/cart/' + id, {
          headers: { Authorization: `Bearer ${token}` },
        })
        if (response.data.code === 1) {
          this.getOrderData()
        }
      } catch (error) {
        console.error('删除失败', error)
      }
    },
    getOrderData() {
      const token = localStorage.getItem('jwtToken')

      this.$http
        .get('/api/adminhome/order', {
          headers: { Authorization: `Bearer ${token}` },
        })
        .then((res) => {
          this.OrderData = res.data
          console.log(this.OrderData.data)
        })
        .catch((err) => {
          console.log(err)
        })
    },
    initCharts(data) {
      // 初始化销售数量图表
      const quantityChartDom = document.getElementById('sales-quantity-chart')
      const quantityChart = echarts.init(quantityChartDom)
      const quantityData = data.map((item) => ({
        value: item.quantity,
        name: item.name,
      }))

      quantityChart.setOption({
        title: {
          text: '销售数量统计报表',
          left: 'center',
        },
        tooltip: {
          trigger: 'item',
        },
        legend: {
          bottom: '0%',
          left: 'center',
        },
        series: [
          {
            name: '数量',
            type: 'pie',
            radius: '50%',
            data: quantityData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
          },
        ],
      })

      // 初始化销售金额图表
      const amountChartDom = document.getElementById('sales-amount-chart')
      const amountChart = echarts.init(amountChartDom)
      const amountData = data.map((item) => ({
        value: item.quantity * item.price,
        name: item.name,
      }))

      amountChart.setOption({
        title: {
          text: '销售金额统计报表',
          left: 'center',
        },
        tooltip: {
          trigger: 'item',
        },
        legend: {
          bottom: '0%',
          left: 'center',
        },
        series: [
          {
            name: '金额',
            type: 'pie',
            radius: '50%',
            data: amountData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
          },
        ],
      })
    },
  },
}
</script>

<style scoped>
.header-title {
  padding-left: 200px;
}
.resized-image {
  max-width: 80px;
  max-height: 80px;
  object-fit: contain;
}
.small-title {
  font-size: 24px;
  margin-bottom: 20px;
  padding-left: 5px;
  text-align: left;
}
.charts-container {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.chart {
  width: 48%;
  height: 400px;
}
</style>
